<!--货品类型-->
<template>
    <el-form :model="typeform" ref="typeref"  :inline="true" style="text-align: left;">
        <el-form-item label="货品类型:" prop="typename">
            <el-input placeholder="请输入货品类型名称" v-model="typeform.typename" ></el-input>
        </el-form-item>
        <el-form-item label="状态:" prop="status">
            <el-select placeholder="请选择" v-model="typeform.status"  style="width:200px">
                 <el-option value="0" label="启用">启用</el-option>
                 <el-option value="1" label="禁用">禁用</el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="操作人:" prop="createname">
            <el-input placeholder="请输入" v-model="typeform.createname" ></el-input>
        </el-form-item>
        <el-form-item label="操作时间:" prop="timeRange">
            <el-date-picker v-model="typeform.timeRange" :value-format="dateFormat" type="datetimerange"
                range-separator="To" start-placeholder="Start date" end-placeholder="End date" />
        </el-form-item>
        <el-form-item>
            <el-button @click="Reset">重置</el-button>
            <el-button type="success" @click="Search">查询</el-button>
        </el-form-item>
    </el-form>
    <div style="text-align: left;">
        <el-button type="success" @click="showAddDrawer()">添加</el-button>
        <el-button @click="Import">导入</el-button>
        <el-button @click="Export">导出</el-button>
    </div>
    <!--表格-->
    <el-table :data="typedata" stripe style="margin-top: 10px;" row-key="type_id" default-expand-all :tree-props="{ children: 'children'}" @selection-change="SelectChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="type_id" label="序号"></el-table-column>
        <el-table-column prop="type_code" label="货品类型编号"></el-table-column>
        <el-table-column prop="type_name" label="货品类型名称"></el-table-column>
        <el-table-column prop="type_status" label="状态"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="create_name" label="操作人"></el-table-column>
        <el-table-column prop="create_time" label="操作时间"></el-table-column>
        <el-table-column label="操作" width="300">
            <template #default="scope">
                <el-button type="success" text="编辑" @click="ShowUpdate(scope.row.type_id)">编辑</el-button>
                <el-button type="primary" text="增加下级" @click="showAddDrawer(scope.row)">增加下级</el-button>
                <el-button type="danger" text="删除" @click="ShowDelete(scope.row.type_id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

     <!-- 页码 -->
    <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
        v-on:current-change="handlePageChange" style="float:right;margin-top:20px">
    </el-pagination>

    <!--添加抽屉-->
    <el-drawer v-model="drawer">
        <template #header>
            <h4 style="text-align: left;">添加</h4>
        </template>
        <template #default>
            <el-form :model="addform" ref="addformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-form-item label="货品类型编号">
                    <el-input placeholder="自动获取系统编号" disabled></el-input>
                </el-form-item>
                <el-form-item label="货品类型名称" prop="name">
                    <el-input placeholder="请输入货品类型名称" v-model="addform.name"></el-input>
                </el-form-item>
                <el-form-item label="上级分类" prop="pid">
                    <el-tree-select v-model="addform.pid" :data="types"
                        :props="{
                            value: 'type_id',
                            label: 'type_name',
                            children: 'children'
                        }"
                        placeholder="请选择"
                        style="width: 200px"
                        check-strictly
                        default-expand-all/>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input placeholder="请输入" v-model="addform.sort"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="addform.status">
                        <el-radio value="0">启用</el-radio>
                        <el-radio value="1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" placeholder="请输入" v-model="addform.remark"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="Add">确定</el-button>
            </div>
        </template>
    </el-drawer>

    <!--修改抽屉-->
    <el-drawer v-model="drawer2">
        <template #header>
            <h4 style="text-align: left;">修改</h4>
        </template>
        <template #default>
            <el-form :model="updateform" ref="updateformref" :rules="rules" label-width="auto" style="text-align: left;">
                <el-form-item label="货品类型编号">
                    <el-input placeholder="自动获取系统编号" disabled v-model="updateform.code"></el-input>
                </el-form-item>
                <el-form-item label="货品类型名称" prop="name">
                    <el-input placeholder="请输入货品类型名称" v-model="updateform.name"></el-input>
                </el-form-item>
                <el-form-item label="上级分类" prop="pid">
                    <el-tree-select v-model="updateform.pid" :data="types"
                        :props="{
                            value: 'type_id',
                            label: 'type_name',
                            children: 'children'
                        }"
                        placeholder="请选择"
                        style="width: 200px"
                        check-strictly
                        default-expand-all/>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input placeholder="请输入" v-model="updateform.sort"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="updateform.status">
                        <el-radio value="0">启用</el-radio>
                        <el-radio value="1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" placeholder="请输入" v-model="updateform.remark"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="drawer2 = false">取消</el-button>
                <el-button type="primary" @click="Update">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script>
import {ref,reactive,onMounted, nextTick } from 'vue';
import http from '../auth/index';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import * as XLSX from 'xlsx';
export default {
setup()
    {
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));
        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //查询所有货品类型绑定到下拉框
        const types=ref([]);
        function AllType(){
            http.get("/ProductType/GetAllProductTypes")
            .then(res=>{
                const treeData = convertToTree(res.data);
                types.value = [{ type_id: 0, type_name: '无' }, ...treeData];
            }).catch(err=>{
                console.log(err);
            })
        }

        //规则验证
        const rules = reactive({
            name: [
                { required: true, message: '请输入货品类型名称', trigger: 'blur' },
            ],
            sort: [
                { required: true, message: '请输入', trigger: 'blur' },
                { pattern: /^\d+$/, message: '只能是数字', trigger: 'blur' }
            ]
        });

        //当前codeid
        const typeid=ref(0);

        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }

        //导出
        function Export(){
            if(selectdata.value.length==0){
                ElMessage({
                    message: '请选择要导出的数据.',
                    type: 'warning',
                })
                return;
            }
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 准备数据
            const excelData = selectdata.value.map((row) => ({
                "序号": row.type_id,
                "货品类型编号": row.type_code,
                "货品类型名称": row.type_name,
                "排序": row.type_sort,
                "状态": row.type_status === 0 ? '启用' : '禁用',
                "备注": row.remark,
                "操作人": row.create_name,
                "操作时间": row.create_time,
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet (excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "货品类型");
            // 导出并下载
            XLSX.writeFile(wb, `货品类型${new Date().toLocaleDateString()}.xlsx`);
        }

        //导入
        function Import() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.xlsx, .xls';
            input.onchange = (event) => {
                const file = event.target.files[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);
                    //导入
                    http.post("/ProductType/ImportProductTypes", formData)
                    .then(res => {
                        const data=res.data;
                        // 成功导入提示
                        if (data.successCount > 0) {
                            ElMessage.success(`成功导入 ${data.successCount} 条数据`);
                        }
                        // 处理重复数据提示
                        if (data.duplicateCount > 0) {
                            // 创建更详细的重复数据提示
                            let duplicateMessage = `发现 ${data.duplicateCount} 条重复数据，未导入<br>`;
                            // 如果有具体重复行信息
                            if (data.errors && data.errors.length > 0) {
                                // 只筛选出重复相关的错误信息
                                const duplicateErrors = data.errors.filter(err => 
                                    err.includes("货品类型编号") || err.includes("货品类型名称"));
                                
                                // 添加到提示信息中
                                duplicateErrors.forEach(err => {
                                    duplicateMessage += `• ${err}<br>`;
                                });
                            }
                            // 使用更明显的提示方式
                            ElMessageBox.alert(duplicateMessage, '重复数据提示', {
                                confirmButtonText: '确定',
                                customClass: 'duplicate-message-box',
                                dangerouslyUseHTMLString: true
                            });
                            // 同时显示一个简短的警告提示
                            ElMessage.warning({
                                message: `发现 ${data.duplicateCount} 条重复数据`,
                            });
                        }
                        All(); // 刷新数据
                    })
                    .catch(err => {
                        console.error('导入错误:', err);
                    });
                }
            };
            input.click();
        }

        //#region 查询
        //表单数据
        const typeref=ref("");
        const typeform=reactive({
            typename:"",
            status:"",
            createname:"",
            timeRange: [null, null],
        })
        //表格数据
        const typedata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);
        //日期格式
        const dateFormat = 'YYYY-MM-DD HH:mm:ss';

        //重置
        function Reset(){
            typeref.value?.resetFields();
            All();
        }

        //查询
        function Search() {
            All();
        }

        // 将扁平数据转换为树状结构的函数，同时保留所有相关节点及其父节点
        function convertToTree(data) {
            // 先创建一个以 type_id 为键的映射表，方便快速查找节点
            const map = {};
            data.forEach(item => {
                map[item.type_id] = { ...item, children: [] };
            });
            const tree = [];
            data.forEach(item => {
                const node = map[item.type_id];
                if (item.type_pid === 0) {
                    // 如果是顶层节点，直接添加到树中
                    tree.push(node);
                } else {
                    const parent = map[item.type_pid];
                    if (parent) {
                        // 如果父节点存在，将当前节点添加到父节点的 children 中
                        parent.children.push(node);
                    } else {
                        // 如果父节点不存在，将其作为顶层节点添加到树中
                        tree.push(node);
                    }
                }
            });
            return tree;
        }

        //查询数据
        function All(){
            http.get("/ProductType/GetProductType", {
                params: {
                    name: typeform.typename,
                    status: typeform.status,
                    createname: typeform.createname,
                    starttime: typeform.timeRange[0],
                    endtime: typeform.timeRange[1],
                    CurrentPage: currentPage.value
                }
            }).then(res => {
                rows.value = res.data.rows;//总量
                if (res.data.list.length == 0) {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item, // 复制原始对象的所有属性
                    create_time: formatDateTime(new Date(item.create_time)),
                    type_status: item.type_status === 0 ? '启用' : '禁用'
                }));
                typedata.value = convertToTree(Data);//转为树状展示
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }



        //#endregion

        //#region 添加

        //添加抽屉
        const drawer = ref(false);

        const addformref = ref(null);
        //添加表单
        const addform = reactive({
            code:"",
            name: "",
            pid:0,
            sort:"1",
            status: "0",
            remark: "",
            create_name: user.name,
            create_time: new Date(),
        })
       
        function showAddDrawer(parentRow = null){
            // First, manually reset the form data model to default values
            addform.name = "";
            addform.sort = "1";
            addform.status = "0";
            addform.remark = "";

            if(parentRow){
                // If it's adding a child, set the parent ID
                addform.pid = parentRow.type_id;
            }else{
                // If it's adding a top-level category, set parent ID to 0
                addform.pid = 0;
            }

            // Open the drawer
            drawer.value = true;
            
            // After the drawer has opened and the form is available in the DOM,
            // clear any previous validation messages.
            nextTick(() => {
                addformref.value?.clearValidate();
            });
        }
        
        // 添加
        async function Add() {
            try {
                    // 获取自动生成编号 货品类型16
                    const GeneratedCode = async () => {
                        const res = await http.get("/CodeRule/GeneratedCode?id=16");
                        addform.code = res.data;
                    };
                    // 首先执行生成编号
                    await GeneratedCode();

                    //添加
                    addformref.value.validate((valid) => {
                    if (valid) {
                        //添加数据
                        const adddata = {
                            type_code: addform.code,
                            type_name: addform.name,
                            type_pid: addform.pid,
                            type_sort: addform.sort,
                            type_status: addform.status,
                            remark: addform.remark,
                            create_name: addform.create_name,
                            create_time: formatDateTime(addform.create_time),
                        }
                        http.post("/ProductType/AddProductType",adddata)
                        .then(res => {
                            if (res.data> 0) {
                                ElMessage({
                                    message: '添加成功.',
                                    type: 'success',
                                })
                                All();
                                //清除表单
                                addformref.value?.resetFields();
                                AllType();
                            }
                        }).catch(err => {
                            console.log(err);
                        })
                    }
                })
            } catch (err) {
                ElMessage({
                    message: '生成编号失败.',
                    type: 'error',
                });
            }
        }


        //#endregion

        //#region 修改

        //修改抽屉
        const drawer2=ref(false);
        //修改表单
        const updateformref=ref("");
        const updateform = reactive({
            id:"",
            code:"",
            name: "",
            pid:"",
            sort:"",
            status: "",
            remark: "",
            update_name: user.name,
            update_time: new Date(),
        })
        //显示修改
        function ShowUpdate(id){
            drawer2.value=true;
            typeid.value=id;
            //根据当前id查询信息
            http.get("/ProductType/GetProductTypeById?id="+id)
            .then(res=>{
                updateform.id=res.data.type_id;
                updateform.code=res.data.type_code;
                updateform.name=res.data.type_name;
                updateform.pid=res.data.type_pid;
                updateform.sort=res.data.type_sort;
                updateform.status=res.data.type_status.toString();
                updateform.remark=res.data.remark;
            }).catch(err=>{
                console.log(err);
            })
        }
        //修改
        function Update(){
            //修改数据
            const updatedata ={
                type_id:updateform.id,
                type_code: updateform.code,
                type_name: updateform.name,
                type_pid: updateform.pid,
                type_sort: updateform.sort,
                type_status: updateform.status,
                remark: updateform.remark,
                update_name: updateform.update_name,
                update_time: formatDateTime(updateform.update_time),
            }
            http.put("/ProductType/UpdateProductType",updatedata)
            .then(res=>{
                if(res.data>0){
                    ElMessage({
                        message: '修改成功.',
                        type: 'success',
                    })
                    All();
                }
            }).catch(err=>{
                console.log(err);
            })
        }

        //#endregion

         //#region 删除

            //删除模态框
            async function ShowDelete(id){
                typeid.value = id;
                try {
                    const response = await http.get(`/ProductType/CheckUsage?id=${id}`);
                    const { hasChildren, hasProducts } = response.data;

                    let message = "确定要删除此货品类型吗？";
                    let title = "删除确认";
                    let confirmButtonText = "确定";

                    if (hasChildren || hasProducts) {
                        message = "当前类型下有下级和货品信息，谨慎删除。是否继续？";
                        title = "警告";
                        confirmButtonText = "继续删除";
                    }

                    ElMessageBox.confirm(message, title, {
                        confirmButtonText: confirmButtonText,
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        Delete();
                    }).catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '已取消删除',
                        });
                    });
                } catch (error) {
                    console.error('删除前检查失败:', error);
                    ElMessage.error('删除前检查失败，请稍后重试');
                }
            }
            function Delete(){
                http.put("/ProductType/DeleteProductType?id="+typeid.value)
                .then(res=>{
                    if(res.data>0){
                        ElMessage({
                            message: '删除成功.',
                            type: 'success',
                        })
                        All();
                    }else{
                        ElMessage.error('删除失败.')
                    }
                }).catch(err=>{
                    console.log(err);
                })
            }

        //#endregion

        //挂载
        onMounted(() => {
            All();
            AllType();
        });


        return{
            user,
            formatDateTime,
            typeref,
            typeform,
            typedata,
            rows,
            currentPage,
            dateFormat,
            Reset,
            Search,
            All,
            handlePageChange,
            convertToTree,
            drawer,
            addform,
            addformref,
            Add,
            types,
            AllType,
            rules,
            drawer2,
            updateform,
            updateformref,
            Update,
            ShowUpdate,
            typeid,
            Delete,
            ShowDelete,
            Export,
            selectdata,
            SelectChange,
            Import,
            showAddDrawer
        }
    }
}
</script>

<style scoped>

</style>